package com.easipass.sys.config;

import com.easipass.business.constant.BusinessCode;
import com.easipass.commons.result.constant.ResultErrorCode;
import com.easipass.commons.result.dto.RestBizResult;
import com.easipass.commons.result.dto.RestResult;
import com.easipass.commons.result.exception.ResultBaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局的异常处理类
 */
@ControllerAdvice(annotations = {RestController.class , Controller.class})
@ResponseBody
@Slf4j
public class GlobalRestExceptionHandler {

    @Autowired
    HttpServletRequest request;

    @ExceptionHandler(value = ResultBaseException.class)
    public RestResult easiBaseSysExceptionHandler(ResultBaseException e) {
        RestResult restResult = new RestBizResult(e.getCode() , e.getMessage() , e.getBizCode() , e.getBizMessage());
        return restResult;
    }

    @ExceptionHandler(value = NullPointerException.class)
    public RestResult nullPointerExceptionHandler(Exception e) {
        RestResult restResult = new RestResult(BusinessCode.CODE_500004);
        return restResult;
    }

    @ExceptionHandler(value = org.springframework.web.client.RestClientException.class)
    public RestResult restClientExceptionHandler(Exception e) {
        RestBizResult restResult = new RestBizResult(ResultErrorCode.ERROR_CODE902);
        return restResult;
    }

    @ExceptionHandler(value = Exception.class)
    public RestResult exceptionHandler(Exception e) {
        log.error(e.getMessage() , e);
        RestResult restResult = RestResult.F();
        return restResult;
    }
}
